//
//  FileReadyViewController.swift
//  AutoPrint
//
//  Created by David on 2016/12/4.
//  Copyright © 2016年 fatcat. All rights reserved.
//

import UIKit

class FileReadyViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIAlertViewDelegate, FileUploadViewDelegate, UIDocumentInteractionControllerDelegate  {
    
    var step0VC: UIViewController?
    
    let DOCUMENT_PATH = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
    
    let ASK_BEFORE_EXIT_ALERT_ID = 101
    
    var tableView: UITableView!
    
    var files: [UDFile] = [] // 文件列表
    var fileUploadControls: [FileUploadView] = [] // 文件上传控制
    
    var bottomBar: UIView! // 底部栏
    var submitBtn: UIButton! // 提交订单按钮
    
    convenience init(files: [UDFile], step0VC: UIViewController){
        self.init()
        self.files = files
        self.step0VC = step0VC
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        title = "上传文件"
        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: #selector(FileReadyViewController.askBeforeExit))
        
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: nil, action: nil)
        
        // MARK: progress retryBtn 做成对象数组 支持多文件上传
        for file in files{
            let fileControl = FileUploadView(file: file)
            fileControl.delegate = self
            fileUploadControls.append(fileControl)
            fileControl.uploadFile()
        }
        
        tableView = UITableView(frame: view.frame, style: .Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.keyboardDismissMode = .OnDrag
        tableView.separatorStyle = .None
        tableView.allowsSelection = false
        view.addSubview(tableView)
        
        // MARK: 底部栏
        bottomBar = UIView(frame: CGRect(x: -0.5, y: view.bounds.height - 48, width: view.bounds.width+1, height: 48))
        bottomBar.backgroundColor = UIColor.whiteColor()
        bottomBar.layer.borderColor = UIColor.lightGrayColor().CGColor
        bottomBar.layer.borderWidth = 0.5
        view.addSubview(bottomBar)
        
        // MARK:提交按钮
        submitBtn = UIButton(frame: CGRect(x: view.bounds.width - 119, y: 0, width: 120, height: 48))
        submitBtn.backgroundColor = UIColor.lightGrayColor()
        submitBtn.setTitle("下一步", forState: .Normal)
        submitBtn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        submitBtn.enabled = false
        bottomBar.addSubview(submitBtn)
        submitBtn.addTarget(self, action: #selector(FileReadyViewController.nextStep), forControlEvents: .TouchUpInside)
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4*files.count
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.row % 4 == 0{
            return 64
        }
        if indexPath.row % 4 == 3{
            return 52
        }
        return 44
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 72
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .Default, reuseIdentifier: "item")
        let fileIndex = indexPath.row / 4
        let order = indexPath.row % 4
        switch order {
        case 0: // MARK: 上传文件
            
            cell.addSubview(fileUploadControls[fileIndex].createUploadView(CGRect(x: 0, y: 0, width: view.bounds.width, height: 64)))
            
            break
        case 1: // MARK: 页数
            cell.addSubview(fileUploadControls[fileIndex].createPageNumView(CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)))
            
            break
        case 2:// MARK: 单面双面 黑白彩印
            cell.addSubview(fileUploadControls[fileIndex].createOptionView(CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)))
            break
        case 3: // MARK: 份数
            cell.addSubview(fileUploadControls[fileIndex].createQuantityView(CGRect(x: 0, y: 0, width: view.bounds.width, height: 44), index: indexPath.row/4))
            break
            
        default:
            break
        }
        return cell
    }
    
    func askBeforeExit(){
        // MARK: 询问是否退出
        let alert = UIAlertView(title: "确定要退出吗?", message: "未上传完成的文件将取消上传", delegate: self, cancelButtonTitle: "不退出")
        alert.tag = ASK_BEFORE_EXIT_ALERT_ID
        alert.addButtonWithTitle("退出")
        alert.show()
        
    }
    
    func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
        if alertView.tag == ASK_BEFORE_EXIT_ALERT_ID {
            if buttonIndex == 1{
                for fileView in fileUploadControls {
                    fileView.cancelUpload()
                }
                navigationController?.popViewControllerAnimated(true)
            }
        }
    }
    func textFieldScrollUp(textField: UITextField) {
        // MARK: 输入框被键盘遮盖时往上移动
        if tableView.contentOffset.y < CGFloat(textField.tag)*204 - 32{
            tableView.setContentOffset(CGPoint(x: 0, y: CGFloat(textField.tag)*204 - 32), animated: true)
        }
        
    }
    
    func didUpdatePrice() {
        var orderReady = true
        for control in fileUploadControls{
            if !control.isFinishedUpload{
                orderReady = false
            }
        }
        
        if orderReady{
            submitBtn.backgroundColor = UIColor.orangeColor()
            submitBtn.enabled = true
        }
    }
    
    func nextStep(){
        let fileInfos = NSMutableArray()
        for file in fileUploadControls{
            let info = NSMutableDictionary()
            info.setObject(file.fileName!, forKey: "file_name")
            info.setObject(file.fileID!, forKey: "file_id")
            info.setObject(file.numOfQuantity, forKey: "goods_number")
            info.setObject(file.numOfPage, forKey: "page_number")
            info.setObject(file.blackWhiteColorOption, forKey: "black_white_color")
            info.setObject(file.singleDoublePageOption, forKey: "single_double")
            
//            if file.blackWhiteColorOption == 1 {
//                info.setObject(Fatcat.PRICE_PRE_PAGE, forKey: "goods_price")
//            }else if file.blackWhiteColorOption == 2{
//                info.setObject(Fatcat.PRICE_PRE_COLOR_PAGE, forKey: "goods_price")
//            }
            fileInfos.addObject(info)
        }
        hidesBottomBarWhenPushed = true
        let shopSelVC = ShopSelectViewController(files: fileInfos)
        shopSelVC.step0VC = self.step0VC
        navigationController?.pushViewController(shopSelVC, animated: true)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func jumpToPreViewFile(onlineFile: Bool, filePath: String, fileName: String) {
        // MARK:  点击预览按钮
        if onlineFile{
            presentViewController(HTMLStringViewController(path: filePath, name: fileName), animated: true, completion: nil)
        }else{
            let urlEncodeString = "file://\(filePath)".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
            let fileURL = NSURL(string: urlEncodeString)!
            let docPVC = UIDocumentInteractionController(URL: fileURL)
            docPVC.delegate = self
            docPVC.presentPreviewAnimated(true)
        }
    }
    
    func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
    
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
